<?php

$file_handle = fopen("conf.txt", "r");
        $line = split(":",fgets($file_handle));

        $hostname= $line[0];
        $db_user= $line[1];
        $db_pass= $line[2];
        $db_name= chop($line[3]);

        fclose($file_handle);
        
       $con = mysql_connect($hostname,$db_user,$db_pass);
       
        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }
        date_default_timezone_set('UTC');
        mysql_select_db($db_name, $con);

if ( $_POST['oper'] == 'add'){
    
        $nombre = $_POST['nombre'];
        $autor = $_POST['autor'];
        $informes = $_POST['informes'];
        $txt = $_POST['comentario'];
        $parametros = '';
               
        $ids = explode(',',$informes);
        foreach($ids as $id){
            $result = mysql_query("SELECT id,parametros FROM informe WHERE id=$id");
            $row = mysql_fetch_array($result);
            if ($parametros == ''){
                $parametros = $row['parametros'];
            }
            else{
                $parametros = $parametros.",". $row['parametros'];
            }
            
        }
        
        //$sql="INSERT INTO informe_final(nombre, parametros, autor, informes, comentario)VALUES('$nombre','$parametros','$autor','$informes','$txt');";
        $sql="INSERT INTO informe_final(nombre,autor, informes, parametros, comentario)VALUES('$nombre','$autor','$informes','$parametros','$txt');";
        $result=mysql_query($sql);
        
        if($result){
            //exito
        }

}
elseif ( $_POST['oper'] == 'del'){
        
        $id = $_POST['id'];
        
        $sql = 'DELETE FROM informe_final WHERE id="'.$id.'"';
        
        $result=mysql_query($sql);

        if($result){
            //exito
        }
        
        
}
elseif ($_POST['oper'] == 'edit') {
        
        $id = $_POST['id'];
        $nombre = $_POST['name'];
        $comment = $_POST['comment'];
        $reports = explode(',',$_POST['reports']);
        
        $error = false;
        
        foreach($reports as $informe_id){
            $sql = 'SELECT id FROM informe WHERE id='.$informe_id;
            $result = mysql_query($sql);
            $row = mysql_fetch_array($result);
            if (empty($row)){
                $error = true;
            }
        }
        
        if ($error){
            echo 0;
        }
        else{
            $sql = 'UPDATE informe_final SET nombre="'.$nombre.'", comentario="'.$comment.'", informes="'.$_POST['reports'].'" WHERE id="'.$id.'"';

            $result=mysql_query($sql);

            if($result){
                echo 1;
            }
        }
        
        
}

mysql_close($con);

?>
